<?php

namespace app\v1\controller;

use support\Request;
use app\model\BizGoodsTicketModel;
use app\model\BizGoodsOrderModel;
use app\model\UserModel;
use support\Log;
use app\model\BizAdminModel;
use Exception;
use app\model\Util;

/**
 * 核销码控制器
 * 用于处理核销码的查询、使用等操作
 */
class BizGoodsTicketController
{
    /**
     * 获取用户订单的核销码列表
     * @param Request $request
     * @return \support\Response
     */
    public function getUserTickets(Request $request)
    {
        try {
            $user = $request->userLogin;
            $orderId = $request->get('order_id');
            
            if (empty($orderId)) {
                return json([
                    'code' => 0,
                    'msg' => '订单ID不能为空',
                    'data' => null
                ]);
            }
            
            // 验证订单是否属于当前用户
            $order = BizGoodsOrderModel::where('id', $orderId)
                ->where('user_id', $user->id)
                ->first();
                
            if (!$order) {
                return json([
                    'code' => 0,
                    'msg' => '订单不存在或无权限查看',
                    'data' => null
                ]);
            }
            
            // 获取核销码列表
            $tickets = BizGoodsTicketModel::where('order_id', $orderId)
                ->orderBy('id', 'desc')
                ->get();
                
            foreach ($tickets as &$ticket) {
                $ticket['status_text'] = BizGoodsTicketModel::STATUS_TEXT[$ticket->status];
                $ticket['created_at'] = date('Y-m-d H:i:s', $ticket->created_at);
                $ticket['expired_at'] = date('Y-m-d H:i:s', $ticket->expired_at);
                $ticket['used_at'] = $ticket->used_at ? date('Y-m-d H:i:s', $ticket->used_at) : '';
            }
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $tickets
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取用户核销码失败: ' . $e->getMessage());
            return json([
                'code' => 0,
                'msg' => '获取失败',
                'data' => null
            ]);
        }
    }
    
    /**
     * 核销码使用
     * @param Request $request
     * @return \support\Response
     */
    public function useTicket(Request $request)
    {
        try {
            $user = $request->userLogin;
            $input = $request->post('data');
            $code = $input['code'];
            
            if (empty($code)) {
                throw new Exception('核销码不能为空');
            }
            
            // 查找核销码
            $ticket = BizGoodsTicketModel::where('code', $code)->first();
            
            if (!$ticket) {
                throw new Exception('核销码不存在');
            }
            
            // 检查核销码状态
            if ($ticket->status == 1) {
                throw new Exception('核销码已使用');
            }
            
            // 检查是否过期
            if ($ticket->expired_at > 0 && $ticket->expired_at < time()) {
                throw new Exception('核销码已过期');
            }
            
            // 检查当前用户是否有权核销
            $admin = BizAdminModel::where('user_id', $user->id)->where('biz_id', $ticket->biz_id)->first();
            if (!$admin) {
                throw new Exception('当前用户无权核销');
            }
            
            // 使用核销码
            $ticket->status = 1;
            $ticket->used_at = time();
            $ticket->updated_at = time();
            $ticket->save();
            
            // 获取订单信息
            $order = BizGoodsOrderModel::find($ticket->order_id);
            $user = UserModel::find($order->user_id);
            
            return json([
                'code' => 1,
                'msg' => '核销成功',
                'data' => [
                    'ticket_id' => $ticket->id,
                    'order_id' => $ticket->order_id,
                    'user_phone' => $user ? $user->phone : '',
                    'used_at' => date('Y-m-d H:i:s', $ticket->used_at)
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    //get-ticket-list-by-biz
    public function getTicketListByBiz(Request $request){
        try {
            $user = $request->userLogin;
            $page = $request->get('page', 1);
            $limit = $request->get('limit', 10);

            $bizAdmin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$bizAdmin) {
                throw new Exception('当前用户无权获取核销码列表');
            }

            $offset = ($page - 1) * $limit;

            $query = BizGoodsTicketModel::with(['bizGoods'])
                ->where('biz_id', $bizAdmin->biz_id)
                ->orderBy('created_at', 'desc');

            // 获取总数
            $total = $query->count();

            // 获取分页数据
            $tickets = $query->offset($offset)->limit($limit)->get();

            $ticketList = [];
            foreach ($tickets as $ticket) {
                $ticketData = [
                    'id' => $ticket->id,
                    'code' => $ticket->status == 1 ? $ticket->code : $ticket->safeCode(),
                    'status' => $ticket->status,
                    'status_text' => BizGoodsTicketModel::STATUS_TEXT[$ticket->status],
                    'expired_at' => $ticket->expired_at < time(),
                    'expired_at_txt' => date('Y-m-d H:i:s', $ticket->expired_at),
                    'created_at' => $ticket->created_at,
                    'created_at_txt' => date('Y-m-d H:i:s', $ticket->created_at),
                    'used_at' => $ticket->used_at,
                    'used_at_txt' => $ticket->used_at ? date('Y-m-d H:i:s', $ticket->used_at) : '',

                    'goods_title' => $ticket->bizGoods->title,
                    'goods_image' => Util::pathToUrl($ticket->bizGoods->image),
                ];

                $ticketList[] = $ticketData;
            }

            // 计算是否有更多数据
            $hasMore = ($offset + $limit) < $total;

            return json([
                'code' => 1,
                'data' => [
                    'list' => $ticketList,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'has_more' => $hasMore
                ],
                'msg' => '获取核销码列表成功'
            ]);
        }catch(Exception $e){
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
} 